import { Provide } from "@midwayjs/decorator";
import { InjectEntityModel } from "@midwayjs/typegoose";
import { ReturnModelType } from "@typegoose/typegoose";
import { Tool } from "../entity/tool";
import { User } from "../entity/user";
import { RespInfo, RespStatusCode } from "../types/common.type";
import { RespMethod } from "../util/common.method";


@Provide()
export class ToolService {

  @InjectEntityModel(User)
  userModel: ReturnModelType<typeof User>;

  @InjectEntityModel(Tool)
  toolModel: ReturnModelType<typeof Tool>;

  /** 创建工具 */
  async add(useruid: string, logo: string, href: string, title: string, type: string, remark: string,): Promise<RespInfo> {
    if (await this.toolModel.findOne({ href })) {
      return RespMethod({}, RespStatusCode.Error, '该网站已被收录')
    } else {
      const user = await this.userModel.findOne({ uid: useruid })
      const info = await this.toolModel.create({ user, logo, href, title, type, remark })
      return RespMethod({ info })
    }
  }

  /** 修改工具 */
  async updated(uid: string, logo: string, href: string, title: string, type: string, remark: string,): Promise<RespInfo> {
    const info = await this.toolModel.updateOne({ logo, href, title, type, remark }).where({ uid })
    return RespMethod({ info })
  }

  /** 删除工具 */
  async delete(uid: string): Promise<RespInfo> {
    await this.toolModel.deleteOne({ uid })
    return RespMethod({})
  }

  /** 工具 list */
  async list(type?: string): Promise<RespInfo> {
    let list = [];
    if (type) {
      list = await this.toolModel.find({ type }).populate('user', 'uid nick avatar').sort([['created', -1]])
    } else {
      list = await this.toolModel.find({}).populate('user', 'uid nick avatar').sort([['created', -1]])
    }
    return RespMethod({ list })
  }

}